package com.raft.kvstore.message;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;

/**包装了命令和客户端
 * @author zhangsulei
 *
 * @param <T>
 */
public class CommandRequest<T> {

    private final T command;
    private final Channel channel;

    public CommandRequest(T command, Channel channel) {
        this.command = command;
        this.channel = channel;
    }

    /**响应结果
     * @param response
     */
    public void reply(Object response) {
        this.channel.writeAndFlush(response);
    }

    /**关闭时的监听器，主要是考虑到客户端可能设置了超时时间，假如指定超时时间内日志没有被commit连接就关闭了，那么就无法回复客户端了
     * @param runnable
     */
    public void addCloseListener(Runnable runnable) {
        this.channel.closeFuture().addListener((ChannelFutureListener) future -> runnable.run());
    }

    /**获取命令
     * @return
     */
    public T getCommand() {
        return command;
    }

}
